<template>
  <div>
    <el-dialog
      :close-on-click-modal="false"
      v-model="visibleDialog"
      :title="props.title"
      align-center
      destroy-on-close
      draggable
      @close="closeDialog"
      style="max-width: 1000px; min-width: 750px"
    >
      <el-form
        ref="formRef"
        :model="formData"
        :rules="rules"
        label-width="90px"
        style="width: 100%"
        class="require-form"
      >
        <!-- 只读状态显示遮罩 -->
        <div v-show="isReadonly" class="formCover"></div>

        <el-form-item label="工作任务" prop="taskName">
          <el-input
            v-model="formData.taskName"
            placeholder="请输入工作任务"
            clearable
          />
        </el-form-item>

        <el-row>
          <el-col :span="12">
            <el-form-item label="序号" prop="seq">
              <el-input
                v-model="formData.seq"
                placeholder="请输入序号"
                clearable
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="负责人" prop="leaderName">
              <SelectPerson
                :maxCollapseTags="5"
                :isMultiple="false"
                :width="`100%`"
                :showSelectPerson="selectPersonData"
                @get-person="getPerson"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-row>
          <el-col :span="12">
            <el-form-item label="开始日期" prop="planStartDate">
              <el-date-picker
                v-model="formData.planStartDate"
                value-format="YYYY-MM-DD"
                format="YYYY-MM-DD"
                clearable
                type="date"
                placeholder="请选择开始日期"
              />
            </el-form-item>
          </el-col>
          <el-col :span="12">
            <el-form-item label="结束日期" prop="planEndDate">
              <el-date-picker
                v-model="formData.planEndDate"
                value-format="YYYY-MM-DD"
                format="YYYY-MM-DD"
                clearable
                type="date"
                placeholder="请选择结束日期"
              />
            </el-form-item>
          </el-col>
        </el-row>

        <el-form-item label="备注" prop="">
          <el-input
            v-model="formData.remarks"
            placeholder="请输入备注"
            type="textarea"
            show-word-limit
            :maxlength="255"
            :autosize="{ minRows: 2, maxRows: 3 }"
          />
        </el-form-item>

        <!-- <el-divider /> -->
        <div class="planList plantasks">
          <div class="header">
            <span class="title">进度计划</span>
            <el-button
              v-show="!isReadonly"
              type="primary"
              small
              @click="handlePlanAdd"
              >新增</el-button
            >
          </div>

          <el-table
            :data="formData.plans"
            style="width: 100%"
            :key="Math.random"
            max-height="300"
            :border="true"
          >
            <el-table-column label="序号" props="seq" width="85">
              <template #default="{ $index, row }">
                <!-- 分行校验的关键在于:prop="'plans.' + $index + '.name'" -->
                <el-form-item
                  :prop="'plans.' + $index + '.seq'"
                  :rules="rules.seq"
                  label-width="0px"
                  class="center-input"
                >
                  <el-input v-model="row.seq" placeholder="请输入" small />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="remarks" label="事项">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'plans.' + $index + '.remarks'"
                  :rules="rules.things"
                  label-width="0px"
                >
                  <el-input v-model="row.remarks" placeholder="请输入事项" />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="planFinishDate" label="完成日期" width="150">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'plans.' + $index + '.planFinishDate'"
                  :rules="rules.planFinishDate"
                  label-width="0px"
                >
                  <el-date-picker
                    v-model="row.planFinishDate"
                    value-format="YYYY-MM-DD"
                    format="YYYY-MM-DD"
                    clearable
                    type="date"
                    placeholder="请选择完成日期"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="completionDegree" label="完成度" width="120">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'plans.' + $index + '.completionDegree'"
                  :rules="rules.completionDegree"
                  label-width="0px"
                  class="right-input"
                >
                  <el-input v-model="row.completionDegree" placeholder="请输入">
                    <template #suffix><span>%</span></template>
                  </el-input>
                </el-form-item>
              </template>
            </el-table-column>

            <el-table-column
              fixed="right"
              align="center"
              label="操作"
              width="80"
            >
              <template #default="scope">
                <el-button
                  type="danger"
                  link
                  class="mt-[-10px]"
                  @click.stop="handleDeleteplan(scope.$index)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>

        <div class="planList plantasks mt-[10px]">
          <div class="header">
            <span class="title">量化指标</span>
            <el-button
              v-show="!isReadonly"
              type="primary"
              small
              @click="handleAdd"
              >新增</el-button
            >
          </div>

          <el-table
            :data="formData.grossProfits"
            style="width: 100%"
            :key="Math.random"
            max-height="300"
            :border="true"
          >
            <el-table-column label="序号" props="seq" width="85">
              <template #default="{ $index, row }">
                <!-- 分行校验的关键在于:prop="'grossProfits.' + $index + '.name'" -->
                <el-form-item
                  :prop="'grossProfits.' + $index + '.seq'"
                  :rules="rules.seq"
                  label-width="0px"
                  class="center-input"
                >
                  <el-input v-model="row.seq" placeholder="请输入" small />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="名称" props="indexName">
              <template #default="{ $index, row }">
                <!-- 分行校验的关键在于:prop="'grossProfits.' + $index + '.name'" -->
                <el-form-item
                  :prop="'grossProfits.' + $index + '.indexName'"
                  :rules="rules.indexName"
                  label-width="0px"
                >
                  <el-input
                    v-model="row.indexName"
                    placeholder="请输入名称"
                    small
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="指标" props="planIndexValue" width="85">
              <template #default="{ $index, row }">
                <!-- 分行校验的关键在于:prop="'grossProfits.' + $index + '.name'" -->
                <el-form-item
                  :prop="'grossProfits.' + $index + '.planIndexValue'"
                  :rules="rules.planIndexValue"
                  label-width="0px"
                  class="center-input"
                >
                  <el-input
                    v-model="row.planIndexValue"
                    placeholder="请输入"
                    small
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column label="单位" props="indexUnit" width="100">
              <template #default="{ $index, row }">
                <!-- 分行校验的关键在于:prop="'grossProfits.' + $index + '.name'" -->
                <el-form-item
                  :prop="'grossProfits.' + $index + '.indexUnit'"
                  :rules="rules.indexUnit"
                  label-width="0px"
                >
                  <el-select v-model="row.indexUnit" placeholder="请选择">
                    <el-option
                      v-for="item in useDictionary('IndexUnit')"
                      :key="item.value"
                      :value="item.value"
                      :label="item.label"
                      small
                    />
                  </el-select>
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="remarks" label="描述">
              <template #default="{ $index, row }">
                <!-- 分行校验的关键在于:prop="'grossProfits.' + $index + '.name'" -->
                <el-form-item
                  :prop="'grossProfits.' + $index + '.remarks'"
                  :rules="rules.description"
                  label-width="0px"
                >
                  <el-input
                    v-model="row.remarks"
                    placeholder="请输入描述"
                    small
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column prop="planFinishDate" label="完成日期" width="150">
              <template #default="{ $index, row }">
                <el-form-item
                  :prop="'grossProfits.' + $index + '.planFinishDate'"
                  :rules="rules.planFinishDate"
                  label-width="0px"
                >
                  <el-date-picker
                    v-model="row.planFinishDate"
                    value-format="YYYY-MM-DD"
                    format="YYYY-MM-DD"
                    clearable
                    type="date"
                    placeholder="请选择日期"
                  />
                </el-form-item>
              </template>
            </el-table-column>
            <el-table-column
              fixed="right"
              align="center"
              label="操作"
              width="80"
            >
              <template #default="scope">
                <el-button
                  type="danger"
                  link
                  class="mt-[-10px]"
                  @click.stop="handleDelete(scope.$index)"
                >
                  删除
                </el-button>
              </template>
            </el-table-column>
          </el-table>
        </div>
      </el-form>

      <template #footer>
        <div class="dialog-footer">
          <el-button
            v-show="!isReadonly"
            type="primary"
            :loading="loading"
            @click="handleSubmit"
            >确 定
          </el-button>
          <el-button @click="closeDialog">取 消</el-button>
        </div>
      </template>
    </el-dialog>
  </div>
</template>

<script setup lang="ts">
import request from "@/utils/request";
import { useDictionary } from "@/utils/useTable"; // 引入
import { useRoute } from "vue-router";
import { validateNumber } from "@/utils/commonHooks";
import { validateDegree } from "@/utils/commonHooks";

const route = useRoute();

defineOptions({
  name: "AddWorkTask",
  inheritAttrs: false,
});

const emit = defineEmits(["reset-table", "change-visible"]);

const props = defineProps({
  visible: {
    type: Boolean,
    default: () => {
      return false;
    },
  },
  title: {
    type: String,
    default: () => {
      return "";
    },
  },
  parentTaskId: {
    type: String,
    default: () => {
      return "";
    },
  },
  data: {
    type: Object,
    default: () => {
      return {};
    },
  },
});

const isReadonly = ref(false);
/** 弹窗显示隐藏 */
const visibleDialog = ref(false);
watch(
  () => props.visible,
  (newVal: boolean) => {
    visibleDialog.value = newVal;
    if (newVal && props.title.includes("查看")) {
      isReadonly.value = true;
    } else {
      isReadonly.value = false;
    }
  }
);

/** 定义form信息 */
const rules: any = reactive({
  seq: [
    { required: true, message: "请输入序号", trigger: "blur" },
    { max: 20, message: "序号不能超过20个字符", trigger: "blur" },
  ],
  leaderName: [{ required: true, message: "请选择负责人", trigger: "blur" }],
  taskName: [
    { required: true, message: "请输入工作任务", trigger: "blur" },
    { max: 50, message: "工作任务不能超过50个字符", trigger: "blur" },
  ],
  planStartDate: [
    { required: true, message: "请选择开始日期", trigger: "change" },
    { validator: validateStartTime, trigger: "change" },
  ],
  planEndDate: [
    { required: true, message: "请选择结束日期", trigger: "change" },
    { validator: validateEndTime, trigger: "change" },
  ],
  things: [{ required: true, message: "请输入事项", trigger: "blur" }],
  description: [{ required: true, message: "请输入描述", trigger: "blur" }],
  remarks: [{ required: true, message: "请输入备注", trigger: "blur" }],
  planFinishDate: [
    { required: true, message: "请选择完成日期", trigger: "change" },
    { validator: validatePlanTime, trigger: "change" },
  ],
  indexName: [
    { required: true, message: "请输入名称", trigger: "blur" },
    { max: 20, message: "名称不能超过20个字符", trigger: "blur" },
  ],
  planIndexValue: [
    { required: true, message: "请输入指标", trigger: "blur" },
    {
      validator: validateNumber,
      trigger: "blur",
    },
  ],
  indexUnit: [{ required: true, message: "请选择单位", trigger: "change" }],
  completionDegree: [
    { required: true, message: "请输入完成度", trigger: "blur" },
    {
      validator: validateDegree,
      trigger: "blur",
    },
  ],
});

const formRef = ref(ElForm);
// taskType
const initForm = {
  taskType: 2,
  taskName: "",
  seq: "",
  planStartDate: "",
  planEndDate: "",
  remarks: "",
  id: "",
  leaderName: "",
  leaderId: "",
  keyworkId: route.query.id,
  parentTaskId: props.parentTaskId,
  grossProfits: [
    // {
    //   id: "",
    //   planFinishDate: "",
    //   indexName: "",
    //   planIndexValue: "",
    //   indexUnit: "",
    //   seq: "",
    // },
  ],
  plans: [],
};
let formData = reactive(JSON.parse(JSON.stringify(initForm)));

/** 删除行 */
const handleDelete = (index: any) => {
  formData.grossProfits.splice(index, 1);
};

/** 删除行 */
const handleDeleteplan = (index: any) => {
  formData.plans.splice(index, 1);
};

const onePlan = {
  id: "",
  planFinishDate: "",
  completionDegree: "",
  seq: "",
  remarks: "",
};

const onePlans = {
  id: "",
  planFinishDate: "",
  completionDegree: "",
  seq: "",
  remarks: "",
};

/** 添加行 */
const handleAdd = () => {
  formData.grossProfits.push(JSON.parse(JSON.stringify(onePlan)));
};

/** 添加行 */
const handlePlanAdd = () => {
  formData.plans.push(JSON.parse(JSON.stringify(onePlans)));
};

// 打开人员选择器方法
const selectPersonData: any = ref([]);

function getPerson(Ids: string[], Objects: any) {
  formData.leaderName = Objects[0]?.firstName || "";
  formData.leaderId = Objects[0]?.id || "";
  formRef.value.clearValidate("leaderName");
}

/** 编辑赋值 */
watch(
  () => props.data,
  (newVal: any) => {
    formData.id = "";
    if (newVal?.id) {
      const {
        id,
        parentTaskId,
        taskType,
        taskName,
        seq,
        planStartDate,
        planEndDate,
        remarks,
        leaderName,
        leaderId,
        grossProfits,
        plans,
      } = newVal;
      Object.assign(formData, {
        id,
        taskType,
        parentTaskId,
        taskName,
        seq,
        planStartDate,
        planEndDate,
        remarks,
        leaderName,
        leaderId,
        grossProfits: grossProfits || [],
        plans: plans || [],
      });
      selectPersonData.value = leaderId
        ? [{ id: leaderId, firstName: leaderName }]
        : [];
    }
  }
);

/** 关闭表单弹窗 */
function closeDialog() {
  visibleDialog.value = false;
  emit("change-visible", false);
  resetForm();
}

/** 重置表单 */
function resetForm() {
  formRef.value.resetFields();
  formRef.value.clearValidate();
  // formData.grossProfits = [onePlan];
  selectPersonData.value = [];
  Object.assign(formData, { ...JSON.parse(JSON.stringify(initForm)) });
}

const loading = ref(false);

/** 角色保存提交 */
function handleSubmit() {
  formData.parentTaskId = props.parentTaskId;
  formRef.value.validate(async (valid: any) => {
    let indexNames: any = [];
    formData.grossProfits?.map((e) => {
      indexNames.push(e.indexName);
    });
    const hasDup = hasDuplicates(indexNames);
    if (hasDup) {
      ElMessage.error("量化指标名称不能重复");
      return;
    }
    if (valid && !hasDup) {
      loading.value = true;
      const text = formData.id ? "编辑" : "新增";
      await request({
        url: formData.id
          ? "/system/oakeyworktask/update"
          : "/system/oakeyworktask/save",
        method: "post",
        data: formData,
      }).finally(() => {
        loading.value = false;
      });
      ElMessage.success(`${text}成功`);
      emit("reset-table", formData.id || "");
      closeDialog();
    }
  });
}

// 组件销毁时调用
onBeforeUnmount(() => {
  visibleDialog.value = false;
  emit("change-visible", false);
});

function validateEndTime(rule: any, value: string, callback: (a?: any) => {}) {
  if (formData.planStartDate && value < formData.planStartDate) {
    callback(new Error("结束日期不能小于开始日期"));
  } else {
    formRef.value.clearValidate("planFinishDate");
    callback();
  }
}

function validateStartTime(
  rule: any,
  value: string,
  callback: (a?: any) => {}
) {
  if (formData.planEndDate && value > formData.planEndDate) {
    callback(new Error("开始日期不能大于结束日期"));
  } else {
    callback();
  }
}

function validatePlanTime(rule: any, value: string, callback: (a?: any) => {}) {
  if (formData.planEndDate < value) {
    callback(new Error("计划完成日期不能大于结束日期"));
  } else {
    callback();
  }
}

function hasDuplicates(array: []) {
  return new Set(array).size !== array.length;
}
</script>
<style lang="scss" scoped>
@import url(./add-work-requirement.scss);

.require-form {
  .plantasks {
    :deep(.el-table) {
      .cell.el-tooltip {
        padding: 0 5px !important;
      }
    }
  }
  .planList {
    :deep(.el-table) {
      .cell.el-tooltip {
        padding: 0 5px !important;
      }
    }
  }
}
</style>
